package com.cdx.springcloud.controller;

import com.cdx.springcloud.entity.CommonResult;
import com.cdx.springcloud.entity.Payment;
import com.cdx.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 支付控制器
 * @author chedx
 * @data 2020/12/3 11:31 PM
 */
@RestController
@Slf4j
public class PaymentController {
    @Resource
    private PaymentService paymentService;
    @Resource
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String serverPort;

    @PostMapping("/payment/create")
    public CommonResult create(@RequestBody Payment payment) {
        int result = paymentService.create(payment);
        log.info("***********bb插入数据结果："+ result);
        if(result > 0) {
            return new CommonResult(200,"插入数据库成功,端口号：" + serverPort,result);
        }
        return new CommonResult(444, "插入数据库失败,端口号：" + serverPort,null);
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentById(id);
        log.info("***********查询结果数据结果："+ payment);
        if(payment != null) {
            return new CommonResult(200,"查询数据库成功,端口号：" + serverPort,payment);
        }
        return new CommonResult(444, "查询数据库失败,id:" + id,null);
    }

    @GetMapping(value = "/payment/discovery")
    public Object discovery() {
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVER");
        for (ServiceInstance instance : instances) {
            log.info("************instance:" + instance);
        }
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("**************servie:" + service);
        }
        return discoveryClient;
    }

    @GetMapping(value = "/payment/lb")
    public String getLB() {
        return serverPort;
    }

    @GetMapping(value = "/payment/time3")
    public String getFeignTimeout() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }


}
